<!--
  * 临/过期预警
  *
-->
<template>
  <!---------- 查询表单form begin ----------->
  <a-form class="query-form-wrapper smart-margin-bottom10 smart-radius-2" :model="queryForm" labelAlign="left">
    <a-row :gutter="[8, 10]">
      <a-col :span="4">
        <a-form-item label="商品名称" class="smart-margin-bottom0">
          <a-input v-model:value.trim="queryForm.goods_name" placeholder="商品名称" allow-clear />
        </a-form-item>
      </a-col>
      <a-col :span="4">
        <a-form-item label="商品编码" class="smart-margin-bottom0">
          <a-input v-model:value.trim="queryForm.no" placeholder="商品编码" allow-clear />
        </a-form-item>
      </a-col>
      <a-col :span="4">
        <a-form-item label="所属仓库" name="warehouse_id" class="smart-margin-bottom0">
          <Select name="Warehouse" v-model:value="warehouse_id" :fetch-params="selectFetchParams.warehouse" placeholder="请选择仓库" @input-enter="onSearch" />
        </a-form-item>
      </a-col>
      <a-col :span="4">
        <a-button-group>
          <a-button type="primary" html-type="submit" @click="onSearch" v-privilege="'goods:query'">
            <template #icon>
              <SearchOutlined />
            </template>
            查询
          </a-button>
          <a-button @click="resetQueryData" v-privilege="'goods:query'">
            <template #icon>
              <ReloadOutlined />
            </template>
            重置
          </a-button>
        </a-button-group>
      </a-col>
    </a-row>
  </a-form>
  <!---------- 查询表单form end ----------->
  <div class="query-table-wrapper">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button @click="onExport" type="primary" v-privilege="'goods:exportGoods'">
          <template #icon>
            <ExportOutlined />
          </template>
          导出
        </a-button>
      </div>
      <div class="smart-table-setting-block">
        <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.BUSINESS.ERP.GOODS" :refresh="queryData" />
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->
    <div class="table-wrapper">
      <a-table
        size="small"
        :dataSource="tableData"
        :columns="columns"
        rowKey="id"
        bordered
        :scroll="{ x: 'max-content', y: tableScrollY }"
        :pagination="false"
        :showSorterTooltip="false"
        :loading="tableLoading"
        :row-selection="{
          selectedRowKeys: selectedRowKeyList,
          onChange: onSelectChange
        }"
        :showExpandColumn="false"
        expandRowByClick
      >
        <template #bodyCell="{ text, record, column }">
          <template v-if="column.dataIndex === 'goods_name'">
            <CopyText :text="text">
              {{ text }}
            </CopyText>
          </template>
          <template v-if="column.dataIndex === 'img'">
            <div class="smart-table-operate">
              <a-image :width="30" :src="text || failImg" />
            </div>
          </template>
          <template v-if="column.dataIndex === 'batch_num'">
            <span>{{ record.batches.length }}</span>
          </template>
        </template>
        <template #expandedRowRender="{ record }">
          <div class="content" style="max-height: 200px; overflow-y: auto">
            <div class="parent" v-for="item in record.batches" :key="item.id">
              <div class="div1">批次：{{ dayjs(item.batch_time).format('YYYY-MM-DD') }}</div>
              <div class="div2">数量：{{ transformSpec(item.quantity, record?.spec) }}</div>
              <div class="div3">仓库：{{ item.warehouse_name }}</div>
              <!-- 使用 a-tooltip 显示库位 -->
              <a-tooltip>
                <template #title>{{ item.code }}</template>
                <div class="div3">库位：{{ item.code }}</div>
              </a-tooltip>
            </div>
          </div>
        </template>
      </a-table>
    </div>

    <div class="smart-query-table-page query-table-page">
      <a-pagination showSizeChanger showQuickJumper show-less-items :pageSizeOptions="PAGE_SIZE_OPTIONS" :defaultPageSize="queryForm.limit" v-model:current="queryForm.page" v-model:pageSize="queryForm.limit" :total="total" @change="queryData" @showSizeChange="queryData" :show-total="() => `共${total}条`" />
    </div>
  </div>
</template>
<script lang="ts" setup>
import dayjs from 'dayjs'
import Select from '@/components/business/select/index.vue'
import { PAGE_SIZE_OPTIONS } from '@/constants/system/common-const'
import { TABLE_ID_CONST } from '@/constants/support/table-id-const'
import { QUERY_FORM_OP } from '@/constants/support/query-form-op-const'
import { WARNING_TYPE_ENUM } from '@/constants/business/storage/warning/warning-const'
import { useQuery } from '@/hooks/web/use-query-hook'
import { WAREHOUSE_TYPE, WAREHOUSE_ATTRIBUTE_TYPE } from '@/constants/business/storage/warehouse/warehouse-const'
import { warningApi } from '@/api/business/storage/warehouse-api'
import { useResize } from '@/hooks/web/use-resize-hook'
import failImg from '@/assets/images/notice/failImg.png'
import { useTransformSpec } from '@/hooks/web/use-transform-spec'
import { useEnums } from '@/hooks/plugins/useEnums'
const { transformSpec } = useTransformSpec()
const { getDescByValue } = useEnums()
// ----------------------------- 计算表格高度 -----------------------------
const { tableScrollY } = useResize()

// ---------------------------- 表格列 ----------------------------

const columns = reactive([
  {
    title: '图片',
    dataIndex: 'img',
    width: 80
  },
  {
    title: '商品名称',
    dataIndex: 'goods_name',
    width: '20%'
  },
  {
    title: '商品编码',
    dataIndex: 'no',
    width: '20%'
  },
  {
    title: '批次数量',
    dataIndex: 'batch_num'
  },
  {
    title: '临/过期数量',
    dataIndex: 'totleNum'
  }
])

// ---------------------------- 查询数据表单和方法 ----------------------------
// 聚合同批次、库位的库存批次数据并换算成可读格式
const formatInventoryBatches = (inventoryBatches: any[]) => {
  const list = new Map()
  for (const item of inventoryBatches) {
    const time = dayjs(item.batch_time).valueOf()
    const key = `${time}-${item?.warehouse?.id}`
    // 将仓库位置的code数组转换为逗号分隔的字符串
    let locationCodes = ''
    if (item.location) {
      locationCodes = item.location.map((location: any) => location.code).join('| ')
    }

    const value = {
      batch_time: time,
      code: locationCodes,
      warehouse_name: `${item?.warehouse?.name}(${getDescByValue('WAREHOUSE_ATTRIBUTE_TYPE', item?.warehouse?.attribute_type)})`,
      quantity: item.quantity,
      goods: item.goods
    }
    if (list.has(key)) {
      const temp = list.get(key)
      temp.quantity += value.quantity

      // 合并code
      const existingCodes = temp.code.split(', ').map((code) => code.trim())
      const newCodes = value.code.split(', ').map((code) => code.trim())
      const combinedCodes = [...new Set([...existingCodes, ...newCodes])].join(', ') // 去重并合并
      temp.code = combinedCodes

      list.set(key, temp)
    } else {
      list.set(key, value)
    }
  }
  return Array.from(list.values()).sort((a, b) => b.batch_time - a.batch_time)
}
const warehouse_id = ref(null)
const { queryForm, tableData, tableLoading, total, resetQuery, onSearch, queryData } = useQuery({
  fetchDataApi: async (params) => {
    const res = await warningApi.queryList({ ...params, warning_type: WARNING_TYPE_ENUM.EXPIRED.value, warehouse_id: warehouse_id.value })
    const list = res.data?.data.map((item) => {
      return {
        ...item,
        large_num: item.large_num == 0 ? '' : item.large_num,
        middle_num: item.middle_num == 0 ? '' : item.middle_num,
        base_num: item.base_num == 0 ? '' : item.base_num,
        batches: formatInventoryBatches(item.batchFilter)
      }
    })
    return {
      list,
      total: res.data.total
    }
  },
  queryFormFilter: {
    goods_name: '',
    no: ''
  },
  queryFormOp: {
    goods_name: QUERY_FORM_OP['模糊查询'],
    no: QUERY_FORM_OP['模糊查询']
  }
})
onMounted(queryData)

const resetQueryData = () => {
  warehouse_id.value = null
  resetQuery()
}

// Select查询参数
const selectFetchParams = {
  warehouse: {
    filter: {
      warehouse_type: WAREHOUSE_TYPE.FIXED.value,
      attribute_type: [WAREHOUSE_ATTRIBUTE_TYPE.WAREHOUSE.value, WAREHOUSE_ATTRIBUTE_TYPE.TEMPORARY.value]
    },
    op: {
      warehouse_type: QUERY_FORM_OP['全等查询'],
      attribute_type: QUERY_FORM_OP['IN查询']
    },
    fields: 'id,name'
  }
}

// 选择表格行
const selectedRowKeyList = ref<number[]>([])

function onSelectChange(selectedRowKeys: number[]) {
  selectedRowKeyList.value = selectedRowKeys
}
// ------------------------------- 导出和导入 ---------------------------------
// 导出
function onExport() {
  const filter = {
    goods_name: queryForm.value.goods_name,
    no: queryForm.value.no
  }
  const op = {
    goods_name: QUERY_FORM_OP['模糊查询'],
    no: QUERY_FORM_OP['模糊查询']
  }
  const data = {
    filter: JSON.stringify(filter),
    op: JSON.stringify(op),
    warning_type: WARNING_TYPE_ENUM.EXPIRED.value,
    warehouse_id: warehouse_id.value
  }
  warningApi.exportXlsx(data)
}
</script>
<style lang="less" scoped>
:deep(.ant-table-expanded-row .ant-table-cell) {
  background-color: #e6f4ff;
}
:deep(.ant-table-expanded-row .ant-table-cell:hover) {
  background-color: #e6f4ff;
}
.content {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.parent {
  // margin-left: 50%;
  // margin-right: 5%;
  display: grid;
  grid-template-columns: 20% 25% 25% 30%;
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}
.parent:last-of-type {
  border-bottom: none;
}

.div3 {
  white-space: nowrap; /* 防止文本换行 */
  overflow: hidden; /* 隐藏溢出的内容 */
  text-overflow: ellipsis; /* 显示省略符号来代表被修剪的文本 */
  width: 100%; /* 设置一个宽度限制，以便文本超出时能看到效果 */
}
</style>
